<template>
    <div class="h3_head">
        <el-input v-model="input" style="width: 240px;float: left;" placeholder="请输入套餐名称" />
        <el-button :icon="Search" @click="searchName()" style="float: left;margin-left: 20px;" circle />
         <span>套餐管理</span>
         <el-button style="float: right;" plain @click="editOrAdd=true;dialogFormVisible = true;">
            新增
         </el-button>
    </div>
    <div>
        <el-table highlight-current-row="true" :data="Result.list" style="width: 100%" height="400">
        <el-table-column prop="name" label="套餐名称" width="150" />
        <el-table-column prop="categoryName" label="分类名称" width="120" />
        <el-table-column prop="price" label="价格" width="100" />
        <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
                <el-tag v-if="scope.row.status === 1" type="success">起售</el-tag>
                <el-tag v-else type="danger">停售</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" width="200" />
        <el-table-column prop="image" label="图片" width="120">
            <template #default="scope">
                <el-image 
                    v-if="scope.row.image"
                    style="width: 50px; height: 50px"
                    :src="`/resource/images/${scope.row.image}`"
                    fit="cover"
                />
                <span v-else>无图片</span>
            </template>
        </el-table-column>
        <el-table-column prop="id" label="操作" width="200" >
            <template #default="scope">
                <el-button type="success" size="small" @click="updateStatus(scope.row, 1)" v-if="scope.row.status === 0">
                    起售
                </el-button>
                <el-button type="warning" size="small" @click="updateStatus(scope.row, 0)" v-if="scope.row.status === 1">
                    停售
                </el-button>
                <el-button type="danger" :icon="Delete" @click="deleteSetmeal(scope.row)" circle />
                <el-button type="primary" :icon="Edit" @click="editOrAdd=false;dialogFormVisible = true;selectSetmeal(scope.row)" circle />
            </template>
        </el-table-column>
        </el-table>
    </div>
    <div class="h3_head">
        <el-pagination 
        style="float: left"
        v-model:page-size="pageSize"
        v-model:current-page="pageNum" 
        @current-change="currentPage" 
        background layout="prev, pager, next" :total="Result.total" />
        <span style="float: right; line-height: 32px">共有{{Result.total}}数据</span>
    </div>

    <!-- 对话框 -->
    <el-dialog v-model="dialogFormVisible" title="套餐信息" width="600px">
    <el-form :model="form">
      <el-form-item label="套餐名称" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="套餐分类" :label-width="formLabelWidth">
        <el-select v-model="form.categoryId" placeholder="请选择套餐分类">
          <el-option 
            v-for="category in categoryList" 
            :key="category.id" 
            :label="category.name" 
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="价格" :label-width="formLabelWidth">
        <el-input v-model="form.price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="状态" :label-width="formLabelWidth">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option label="停售" :value="0" />
          <el-option label="起售" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" :label-width="formLabelWidth">
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
      <el-form-item label="图片" :label-width="formLabelWidth">
        <el-upload
            v-model:file-list="fileList"
            action="/api/admin/common/uploadLocal"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :headers="uploadHeaders"
            limit="1">
            <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="editOrAdd" type="primary"
         @click="dialogFormVisible = false;addSetmeal()">
          确认添加
        </el-button>
        <el-button v-else type="primary" @click="dialogFormVisible = false;updateSetmeal();">
          确认编辑
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
      
<script setup>
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
} from '@element-plus/icons-vue';
import { onMounted, watch } from 'vue';
import axios from 'axios';
import { ref,reactive } from 'vue';


//套餐名称搜索功能
const input = ref('');
const searchName = () =>{
    fetchData()
}

const pageSize = ref(9);
const pageNum = ref(1);
const Result = ref({
  list: [],
  total: 0,
});

//对话框操作
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const editOrAdd = ref(false);
const form = reactive({
  id: '',
  name: '',
  categoryId: '',
  price: '',
  status: 1,
  description: '',
  image: '',
})

// 套餐分类列表
const categoryList = ref([])

// 图片上传相关
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref([])
const uploadHeaders = ref({
  token: sessionStorage.getItem('token') || ''
});

// 获取套餐分类列表（type=2）
const getCategoryList = () => {
    axios({
        url: '/api/admin/category',
        method: 'get',
        headers: {
            token: sessionStorage.getItem('token')
        }
    }).then(res => {
        if (res.data.code === 200) {
            // 过滤出type=2的套餐分类
            categoryList.value = res.data.data.filter(category => category.type === 2);
            console.log('套餐分类列表:', categoryList.value);
        }
    }).catch(error => {
        console.error('获取分类列表失败:', error);
    })
}

//关闭对话框重置表单
watch(dialogFormVisible, (newVal, oldVal) => {
  if (newVal === false) {
    initialForm();
    fileList.value = [];
  }
});

// 定义初始表单状态
const initialForm =()=> {
  form.id= '';
  form.name= '';
  form.categoryId= '';
  form.price= '';
  form.status= 1;
  form.description= '';
  form.image= '';
}

// 图片上传相关方法
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  form.image = "";
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

const handleSuccess = (response, file, fileList) => {
  console.log('服务器返回的字符串:', response);
  console.log('文件对象:', file);
  console.log('文件列表:', fileList);
  
  // 设置文件URL用于显示
  file.url = `/resource/images/${response.data}`; 
  // 保存到表单数据
  form.image = response.data;
  console.log("这是表单的数据："+form.image)
};

// 处理编辑时的图片回显
const handlePictureCardPreview1 = (image) => {
  if (image) {
    fileList.value.push({
      name: image,
      url: "/resource/images/"+image,
      status: 'success'
    })
  }
}

//添加套餐操作
const addSetmeal = () =>{
    axios({
        url:"/api/setmeal",
        method:"post",
        data:{
            name: form.name,
            categoryId: form.categoryId,
            price: form.price,
            status: form.status,
            description: form.description,
            image: form.image,
        },
        headers:{
            token:sessionStorage.getItem('token')
        }
    }).then(res=>{
        if(res.data.code==200){
            alert("添加成功");
            fetchData();
        }else{
            alert("添加失败");
        }
    })
}

//根据id查询套餐
const selectSetmeal = (row) => {
    axios({
        url:"/api/setmeal/"+row.id,
        method:"get",
        headers:{
            token:sessionStorage.getItem('token')
        }
    }).then(res=>{
        if(res.data.code==200){
            form.id = res.data.data.id;
            form.name = res.data.data.name;
            form.categoryId = res.data.data.categoryId;
            form.price = res.data.data.price;
            form.status = res.data.data.status;
            form.description = res.data.data.description;
            form.image = res.data.data.image;
            // 处理图片回显
            handlePictureCardPreview1(res.data.data.image);
        }
    })
}

//修改套餐操作
const updateSetmeal = () =>{
    axios({
        url:"/api/setmeal",
        method:"put",
        data:{
            id: form.id,
            name: form.name,
            categoryId: form.categoryId,
            price: form.price,
            status: form.status,
            description: form.description,
            image: form.image,
        },
        headers:{
            token:sessionStorage.getItem('token')
        }
    }).then(res=>{
        if(res.data.code==200){
            alert("修改成功");
            fetchData();
        }else{
            alert("修改失败");
        }
    })
}

//删除套餐操作
const deleteSetmeal = (row) => {
    axios({
        url:"/api/setmeal/"+row.id,
        method:"delete",
        headers:{
            token:sessionStorage.getItem('token')
        }
    }).then(res=>{
        if(res.data.code==200){
            alert("删除成功");
            fetchData();
        }else{
            alert("删除失败");
        }
    })
}

//更新套餐状态
const updateStatus = (row, status) => {
    axios({
        url:"/api/setmeal/status/"+row.id+"/"+status,
        method:"put",
        headers:{
            token:sessionStorage.getItem('token')
        }
    }).then(res=>{
        if(res.data.code==200){
            alert("状态更新成功");
            fetchData();
        }else{
            alert("状态更新失败");
        }
    })
}

//分页查询套餐数据
const fetchData = () => {
    axios({
        url:"/api/setmeal/page",
        method:"get",
        params:{
            pageNum: pageNum.value,
            pageSize: pageSize.value,
            name: input.value
        },
        headers:{
            token:sessionStorage.getItem('token')
        }
    }).then(res=>{
        if(res.data.code==200){
            Result.value = res.data.data;
        }
    })
}

//分页操作
const currentPage = (newPage) =>{
    pageNum.value = newPage;
    fetchData();
}

onMounted(()=>{
    getCategoryList();
    fetchData();
})
</script>

<style>
.h3_head {
    margin: 20px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style> 